//
//  RWHomeViewController.m
//  04-ipadQQ
//
//  Created by 紫荆秋雪 on 16/4/7.
//  Copyright © 2016年 紫荆秋雪. All rights reserved.
//

#import "RWHomeViewController.h"
#import "RWDock.h"
#import <Masonry.h>

@interface RWHomeViewController ()
/** Dock */
@property (nonatomic,strong) RWDock *dock;

/** 当前显示的控制器 */
@property (nonatomic,strong) UIViewController *showingVC;

@end

@implementation RWHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //0 设置背景颜色
    self.view.backgroundColor = RWColor(55, 55, 55);
    
    //1 保证一开始就监听屏幕的方向
    [self willRotateToInterfaceOrientation:self.interfaceOrientation duration:0];
    
    //2、初始化子控件
    [self setupChilds];
    
    //3、监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observerNotification:) name:RWTabBarDidSelectNotification object:nil];

}

/**
 *  移除监听
 */

- (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 监听“通知”
- (void)observerNotification:(NSNotification *)notification{

    //获取 按钮的tag
    int count = [notification.userInfo[RWTabBarSelectIndex] intValue];
    
    //切换控制器
    [self switchButtonCount:count];
}

#pragma mark - 创建子控制器
- (void)setupChilds{

    //创建子控制器
    for (int i = 0; i < 6; i++) {
        
        //1、创建控制器
        UIViewController *childVC = [[UIViewController alloc] init];
        
        //2、设置控制器背景颜色
        childVC.view.backgroundColor = RWRandomColor;
        
        //把子控制器添加到父控制器中
        [self addChildViewController:childVC];
    }
    
    //初始时
    [self switchButtonCount:0];
}

/**
 *  切换控制器
 */
- (void)switchButtonCount:(NSInteger)count{

    //0 移除当前控制器
    [self.showingVC.view removeFromSuperview];
    
    //1 添加 count控制器view到“父控制器”中
    UIViewController *childVC = self.childViewControllers[count];
    [self.view addSubview:childVC.view];
    
    //2 把当前的控制器赋值给 showingVC
    self.showingVC = childVC;
    
    //3 设置frame
    [childVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.dock.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
        make.right.equalTo(self.view.mas_right);
        
    }];
    
}

#pragma mark - 监听屏幕旋转
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    //判断横竖屏
    if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {//横屏
        
        //设置dock的 横屏尺寸
        self.dock.width = RWDockLW;
        self.dock.height = RWScreenPW;
        
    }else {//竖屏
    
        self.dock.width = RWDockPW;
        self.dock.height = RWScreenLW;
    }
    
}

#pragma mark - 懒加载Dock
- (RWDock *)dock{

    if (_dock == nil) {
        
        _dock = [[RWDock alloc] init];
        
        //添加到 控制器view
        [self.view addSubview:_dock];
    }
    
    return _dock;
}

@end
